/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ch.bbcnet.awesomeplayer;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import nu.xom.*;
import nu.xom.converters.DOMConverter;
import org.hsqldb.lib.MD5;
import org.w3c.dom.DOMImplementation;


/**
 * @author efellf
 */
public class XML {

    String lastStored = null;
    private static XML xml = null;
    static Object[][] data = {};
    static String[] columnNames = {"Titel", "Artist", "Album", "Genre", "Path"};
    public String xmlPath = "";
    public String authXmlPath = "";

    private XML() {
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setzt den Pfad zum playlists.xml file
     *
     * @param xmlPath
     */
    public void setXMLPath(String xmlPath) {
        this.xmlPath = xmlPath;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setzt den Pfad zum auth.xml file
     *
     * @param authXmlPath
     */
    public void setAuthXMLPath(String authXmlPath) {
        this.authXmlPath = authXmlPath;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Lädt die angegebene Playliste in das datenarray
     *
     * @param playlist<span style='font-family:courier new;font-size:9px;'> zu ladende playliste</span>
     *
     */
    public void loadData(String playlist) {
        playlist = playlist.toLowerCase();
        try {
            Builder parser = new Builder();

            Document doc = parser.build(xmlPath);
            Element element = doc.getRootElement();
            data = new Object[element.getChildElements(playlist).get(0).getChildElements("entry").size()][4];
            for (int i = 0; i < element.getChildElements(playlist).get(0).getChildElements("entry").size(); i++) {
                String[] tmp = {
                    element.getChildElements(playlist).get(0).getChildElements("entry").get(i).getAttribute("title").getValue(),
                    element.getChildElements(playlist).get(0).getChildElements("entry").get(i).getAttribute("author").getValue(),
                    element.getChildElements(playlist).get(0).getChildElements("entry").get(i).getAttribute("album").getValue(),
                    element.getChildElements(playlist).get(0).getChildElements("entry").get(i).getAttribute("genre").getValue(),
                    element.getChildElements(playlist).get(0).getChildElements("entry").get(i).getAttribute("path").getValue()
                };
                data[i] = tmp;
            }


        } catch (Exception ex) {
            Logger.getLogger(AwesomePlayer.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;gibt das datenarray zurück
     *
     * @param playlist
     * @return <span style='font-family:courier new;font-size:9px;'>Object[][] data</span>
     */
    public Object[][] getData(String playlist) {
        loadData(playlist);
        return data;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;gibt die Spaltennamen für die Tabelle zurück
     *
     * @return <span style='font-family:courier new;font-size:9px;'>String[] columnNames</span>
     */
    public String[] getColumnNames() {
        return columnNames;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gibt die existierenden Playlisten aus
     *
     * @return <span style='font-family:courier new;font-size:9px;'>String[] playlists</span>
     */
    public String[] getPlaylists() {
        try {
            Builder parser = new Builder();
            Document doc = parser.build(xmlPath);
            Element element = doc.getRootElement();
            List<String> playlists = new ArrayList<String>();
            Arrays.deepToString(playlists.toArray());

            for (int i = 0; i < element.getChildElements().size(); i++) {
                if (!isLocked(element.getChildElements().get(i).getLocalName())) {
                    playlists.add(element.getChildElements().get(i).getLocalName());
                }

            }
            String[] strArray = new String[playlists.size()];
            playlists.toArray(strArray);
            return strArray;

        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public String[] getLockedPlaylists() {
        try {
            Builder parser = new Builder();
            Document doc = parser.build(xmlPath);
            Element element = doc.getRootElement();
            List<String> playlists = new ArrayList<String>();
            Arrays.deepToString(playlists.toArray());

            for (int i = 0; i < element.getChildElements().size(); i++) {
                if (isLocked(element.getChildElements().get(i).getLocalName())) {
                    playlists.add(element.getChildElements().get(i).getLocalName());
                }

            }
            String[] strArray = new String[playlists.size()];
            playlists.toArray(strArray);
            return strArray;

        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
        public String[] getLockedPlaylists(String username){
        List<String> playlists = new ArrayList<String>();
        try {
            Builder parser = new Builder();
            Document doc = parser.build(authXmlPath);
            Element element = doc.getRootElement();
            for(int i = 0; i < element.getChildElements().size();i++){
                Element tmp = element.getChildElements().get(i);
                if(tmp.getAttribute("user").getValue().equals(username)){
                    playlists.add(tmp.getAttribute("list").getValue());
                }
            }
        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
        String[] strArray = new String[playlists.size()];
        playlists.toArray(strArray);
        return strArray;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(Über)schreibt das XML-File
     *
     * @param doc <span style='font-family:courier new;font-size:9px;'>das XOM Dokument
     * @param filename der Filename</span>
     */
    public void writeXmlFile(Document doc, String filename) {
        try {
            // Prepare the DOM document for writing
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            DOMImplementation impl = builder.getDOMImplementation();
            org.w3c.dom.Document w3cDoc = DOMConverter.convert(doc, impl);
// DOM Dokument zum Schreiben vorbereiten
            Source source = new DOMSource(w3cDoc);
            // Outputfile vorbereiten

            StreamResult result = new StreamResult(new File(filename));
            // DOM Dokument schreiben
            Transformer xformer;
            try {
                xformer = TransformerFactory.newInstance().newTransformer();
                xformer.setOutputProperty(OutputKeys.INDENT, "yes");
                xformer.setOutputProperty(OutputKeys.METHOD, "xml");
                xformer.setOutputProperty(OutputKeys.VERSION, "1.0");
                xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                xformer.transform(source, result);
            } catch (TransformerFactoryConfigurationError e) {
                e.printStackTrace();
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Erstellt die Ordnerstruktur für die benötigten files
     */
    public void startUpRoutine(String pathSeperator) {
        String path = "";
        File file;
        File cheat;
        for (int i = 0; i < 2; i++) {
            if (i == 0) {
                path = xmlPath;
            } else if (i == 1) {
                path = authXmlPath;
            }
            file = new File(path);
            String tmp = "";
            String[] tmp2 = path.split(pathSeperator);

            for (int j = 0; j < tmp2.length - 1; j++) {
                tmp += tmp2[j] + pathSeperator;
            }
            cheat = new File(tmp);
            cheat.mkdirs();
            if (!file.exists()) {
                try {
                    file.createNewFile();
                    Builder parser = new Builder();
                    Element root = null;
                    Element newDefaultList = null;
                    Document doc = null;
                    if (i == 0) {
                        root = new Element("playlists");
                        newDefaultList = new Element("musik");
                        root.appendChild(newDefaultList);
                        doc = new Document(root);
                    } else if (i == 1) {
                        root = new Element("users");
                        doc = new Document(root);
                    }



                    this.writeXmlFile(doc, path);
                } catch (IOException ex) {
                    Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Erstellt, wenn nicht vorhanden, eine neue XML-Instanz und gibt sie zurück. Singleton!
     *
     * @return <span style='font-family:courier new;font-size:9px;'>xml-instanz</span>
     */
    public static XML getInstance() {
        if (xml == null) {
            xml = new XML();
        }
        return xml;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Erstellt eine neue Liste mit inhalt
     *
     * @param listname <span style='font-family:courier new;font-size:9px;'>zu erstellende liste
     * @param data abzufüllende daten</span>
     */
    public void createPlaylist(String listname, Object[][] data) {
        listname = listname.replaceAll("[^a-zA-Z]", "_");
        Boolean error = false;
        String[] existingLists = this.getPlaylists();
        for (String string : existingLists) {
            if (string.equals(listname)) {
                error = true;
            }
        }
        try {
            if (!error) {
                Builder parser = new Builder();
                Document doc = parser.build(xmlPath);
                Element element = doc.getRootElement();
                Element newList = new Element(listname);
                Element newEntry = new Element("entry");
                element.appendChild(newList);
                newList.appendChild(newEntry);

                for (int i = 0; i < data.length; i++) {
                    newEntry.addAttribute(new Attribute("artist", (String) data[i][0]));
                    newEntry.addAttribute(new Attribute("album", (String) data[i][1]));
                    newEntry.addAttribute(new Attribute("title", (String) data[i][2]));
                    newEntry.addAttribute(new Attribute("genre", (String) data[i][3]));
                    newEntry.addAttribute(new Attribute("path", (String) data[i][4]));

                }

                this.writeXmlFile(doc, xmlPath);
            }
        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Erstellt eine neue Liste
     *
     * @param listname <span style='font-family:courier new;font-size:9px;'>zu erstellende liste</span>
     */
    public void createPlaylist(String listname) {
        listname = listname.replaceAll("[^a-zA-Z]", "_").toLowerCase();
        Boolean error = false;
        String[] existingLists = this.getPlaylists();
        for (String string : existingLists) {
            if (string.equals(listname)) {
                error = true;
            }
        }
        try {
            if (!error) {
                Builder parser = new Builder();
                Document doc = parser.build(xmlPath);
                Element element = doc.getRootElement();
                Element newList = new Element(listname.trim().replaceAll(" ", "_"));
                element.appendChild(newList);
                this.writeXmlFile(doc, xmlPath);
            } else {
            }
        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Updatet ein Eintrag
     *
     * @param pathToMusicfile <span style='font-family:courier new;font-size:9px;'>der im XML vermerkte pfad
     * @param data neue daten</span>
     */
    public void updateInfos(String pathToMusicfile, Object[] data) {
        try {
            Builder parser = new Builder();
            Document doc = parser.build(xmlPath);
            Element element = doc.getRootElement();

            for (int i = 0; i < element.getChildElements().size(); i++) {
                for (int j = 0; j < element.getChildElements().get(i).getChildElements().size(); j++) {

                    if (element.getChildElements().get(i).getChildElements().get(j).getAttribute("path").getValue().equals(pathToMusicfile)) {

                        element.getChildElements().get(i).getChildElements().get(j).getAttribute("title").setValue(data[0].toString());
                        element.getChildElements().get(i).getChildElements().get(j).getAttribute("author").setValue(data[1].toString());
                        element.getChildElements().get(i).getChildElements().get(j).getAttribute("album").setValue(data[2].toString());
                        element.getChildElements().get(i).getChildElements().get(j).getAttribute("genre").setValue(data[3].toString());
                    }
                }

            }

            this.writeXmlFile(doc, xmlPath);


        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;löscht einträge von einer Playliste
     *
     * @param listname <span style='font-family:courier new;font-size:9px;'>wo soll gelöscht werden?
     * @param data zu löschende daten</span>
     */
    public void deleteFromPlaylist(String listname, Object[] data) {

        try {
            Builder parser = new Builder();
            Document doc = parser.build(xmlPath);
            Element element = doc.getRootElement();
            if (listname.equals("musik")) {
                for (int i = 0; i < element.getChildElements().size(); i++) {
                    for (int j = 0; j < element.getChildElements().get(i).getChildElements().size(); j++) {
                        Element tmp = element.getChildElements().get(i).getChildElements().get(j);
                        if (data[0].toString().equals(tmp.getAttribute("title").getValue())
                                & data[1].toString().equals(tmp.getAttribute("author").getValue())
                                & data[2].toString().equals(tmp.getAttribute("album").getValue())
                                & data[3].toString().equals(tmp.getAttribute("genre").getValue())
                                & data[4].toString().equals(tmp.getAttribute("path").getValue())) {
                            tmp.detach();
                        }
                    }

                }
                this.writeXmlFile(doc, xmlPath);
            } else {

                for (int i = 0; i < element.getChildElements(listname).size(); i++) {
                    for (int j = 0; j < element.getChildElements(listname).get(i).getChildElements().size(); j++) {

                        Element tmp = element.getChildElements(listname).get(i).getChildElements().get(j);
                        if (data[0].toString().equals(tmp.getAttribute("title").getValue())
                                & data[1].toString().equals(tmp.getAttribute("author").getValue())
                                & data[2].toString().equals(tmp.getAttribute("album").getValue())
                                & data[3].toString().equals(tmp.getAttribute("genre").getValue())
                                & data[4].toString().equals(tmp.getAttribute("path").getValue())) {
                            tmp.detach();
                        }
                    }

                }
                this.writeXmlFile(doc, xmlPath);
            }
            this.writeXmlFile(doc, xmlPath);
        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;löscht eine komplette Playliste
     *
     * @param listname <span style='font-family:courier new;font-size:9px;'>zu löschende playlist</span>
     *
     */
    public void deletePlaylist(String listname) {
        //String listnameOriginal = listname;
        listname = listname.toLowerCase();
        listname = listname.replaceAll("[^a-zA-Z]", "_");
        if (listname.equals("musik")) {
            this.fuck("nicolo gang go schiise");
        } else {


            try {
                Builder parser = new Builder();
                Document doc = parser.build(xmlPath);
                Element element = doc.getRootElement();

                for (int i = 0; i < element.getChildElements().size(); i++) {
                    if (element.getChildElements().get(i).getLocalName().toLowerCase().equals(listname)) {
                    	if(isLocked(element.getChildElements().get(i).getLocalName())){
                    		bustLockFromPlaylist(element.getChildElements().get(i).getLocalName());
                    	}
                        element.getChildElements().get(i).detach();
                    }
                }


                this.writeXmlFile(doc, xmlPath);
            } catch (ParsingException ex) {
                //Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Daten in eine Playliste einfügen
     *
     * @param listname <span style='font-family:courier new;font-size:9px;'>name der playliste
     * @param data Object[][] mit den üblichen daten</span>
     */
    public void addToPlaylist(String listname, Object[][] data) {

        try {

            Builder parser = new Builder();
            Document doc = parser.build(xmlPath);
            Element element = doc.getRootElement();
            Element newList = element.getChildElements(listname).get(0);
            Element newEntry = null;


            for (int i = 0; i < data.length; i++) {
                newEntry = new Element("entry");
                newList.appendChild(newEntry);
                newEntry.addAttribute(new Attribute("author", (String) data[i][0]));
                newEntry.addAttribute(new Attribute("album", (String) data[i][1]));
                newEntry.addAttribute(new Attribute("title", (String) data[i][2]));
                newEntry.addAttribute(new Attribute("genre", (String) data[i][3]));
                newEntry.addAttribute(new Attribute("path", (String) data[i][4]));

            }
            this.writeXmlFile(doc, xmlPath);


        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Suche in den Playlisten nach einträgen
     *
     * @param lookFor <span style='font-family:courier new;font-size:9px;'>nach was soll gesucht werden?</span>
     * @param playlist <span style='font-family:courier new;font-size:9px;'>wo soll gesucht werden?</span>
     * @return <span style='font-family:courier new;font-size:9px;'>Object[][] prego fürs JTable :)</span>
     */
    public Object[][] fetchByString(String lookFor, String playlist) {
        lookFor = lookFor.toLowerCase();
        Object[][] output;
        List list = new LinkedList();
        list = new ArrayList();

        try {
            Builder parser = new Builder();
            Document doc = parser.build(xmlPath);
            Element element = doc.getRootElement();
            for (int i = 0; i < element.getChildElements(playlist).size(); i++) {
                for (int j = 0; j < element.getChildElements(playlist).get(i).getChildElements().size(); j++) {
                    Element tmp = element.getChildElements(playlist).get(i).getChildElements().get(j);
                    if (tmp.getAttribute("title").getValue().toLowerCase().contains(lookFor)
                            || tmp.getAttribute("author").getValue().toLowerCase().contains(lookFor)
                            || tmp.getAttribute("album").getValue().toLowerCase().contains(lookFor)
                            || tmp.getAttribute("genre").getValue().toLowerCase().contains(lookFor)) {
                        list.add(new Object[]{tmp.getAttribute("title").getValue(),
                                    tmp.getAttribute("author").getValue(),
                                    tmp.getAttribute("album").getValue(),
                                    tmp.getAttribute("genre").getValue(),
                                    tmp.getAttribute("path").getValue()});
                    }
                }
            }

        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
        output = new Object[list.size()][4];
        for (int i = 0; i < list.size(); i++) {
            output[i] = (Object[]) list.get(i);

        }
        return output;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Bruucht niemmer, wird aber vo aune für witzig ghalte.
     */
    public void fuck(String string) {
        System.err.println(string.toUpperCase());
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Erstellt einen neuen Eintrag in auth.xml
     *
     * @param username <span style='font-family:courier new;font-size:9px;'>
     * @param passwort
     * @param playlist
     * @param passwordIsHashed ist das Passwort bereits gehasht? True = ja, False = nein</span>
     */
    public void lockPlaylist(String username, String passwort, String playlist, Boolean passwordIsHashed) {
        String passwortFinal = null;
        playlist = playlist.toLowerCase();
        playlist = playlist.replaceAll("[^a-zA-Z]", "_");
        if (!passwordIsHashed) {
            try {
                MessageDigest sha1 = MessageDigest.getInstance("SHA1");
                sha1.reset();
                byte[] passwortBytes = passwort.getBytes("UTF-8");
                
                sha1.update(passwortBytes);
                byte[] hashedPassByte = sha1.digest();
                
                StringBuffer tmp = new StringBuffer();
                for (int i = 0; i < hashedPassByte.length; i++) {
                    tmp.append(Integer.toHexString(0xFF & hashedPassByte[i]));
                }
                passwortFinal = tmp.toString();
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            passwortFinal = passwort;
        }
        try {
            Builder parser = new Builder();
            Document doc = parser.build(authXmlPath);
            Element element = doc.getRootElement();
            Element newUser = new Element("entry");
            newUser.addAttribute(new Attribute("pass", passwortFinal));
            newUser.addAttribute(new Attribute("user", username));
            newUser.addAttribute(new Attribute("list", playlist));
            element.appendChild(newUser);
            writeXmlFile(doc, authXmlPath);
        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ist die playliste Gesperrt?
     *
     * @param playlist
     * @return boolean <span style='font-family:courier new;font-size:9px;'>playliste ist gesperrt? True=ja, False=nein</span>
     */
    public boolean isLocked(String playlist) {
        boolean output = false;
        try {

            Builder parser = new Builder();
            Document doc = parser.build(authXmlPath);
            Element element = doc.getRootElement();
            for (int i = 0; i < element.getChildElements("entry").size(); i++) {
                if (element.getChildElements("entry").get(i).getAttribute("list").getValue().toLowerCase().equals(playlist.toLowerCase())) {
                    output = true;
                }

            }
        } catch (ParsingException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
        }
        return output;
    }

    /**
     * <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Versucht eine Benutzer/Passwortkombo zu finden.
     *
     * @param username
     * @param password
     * @param passwordIsHashed
     * @return <span style='font-family:courier new;font-size:9px;'> boolean authentifikation erfolgreich</span>
     */
    public boolean attemptAuth(String username, String password, boolean passwordIsHashed) {

        boolean output = false;
        String passwortFinal = null;
        
        if (!passwordIsHashed) {
            try {
                MessageDigest sha1 = MessageDigest.getInstance("SHA1");
                sha1.reset();
                byte[] passwortBytes = password.getBytes("UTF-8");
                sha1.update(passwortBytes);
                byte[] hashedPassByte = sha1.digest();
                StringBuffer tmp = new StringBuffer();
                for (int i = 0; i < hashedPassByte.length; i++) {
                    tmp.append(Integer.toHexString(0xFF & hashedPassByte[i]));
                }
                passwortFinal = tmp.toString();
                
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
            try {
                Builder parser = new Builder();
                Document doc = parser.build(authXmlPath);
                Element element = doc.getRootElement();
                
                for (int i = 0; i < element.getChildElements("entry").size(); i++) {
                    Element tmp = element.getChildElements("entry").get(i);
                    
                    if (tmp.getAttribute("user").getValue().equals(username) && tmp.getAttribute("pass").getValue().equals(passwortFinal)) {
                        output = true;
                        output = true;
                    }

                }
            } catch (ParsingException ex) {
                Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(XML.class.getName()).log(Level.SEVERE, null, ex);
            }


        

        return output;
    }
/**
 *  <b>Kurzbeschrieb:</b><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Überprüft eine Playlist auf Existenz
 * @param playlist
 * @return boolean existiert die playliste? True = ja, False = nein
 */
    public boolean playlistExists(String playlist) {
        String[] listen = this.getPlaylists();
        for (String str : listen) {
            if (str.toLowerCase().replaceAll("[^a-zA-Z]", "_").equals(playlist.toLowerCase())) {
                return true;
            }
        }
        return false;
    }
    /**
     * 
     * @param playlist
     */
    public void bustLockFromPlaylist(String playlist){
    	playlist = playlist.toLowerCase().replaceAll("[^a-zA-Z]", "_");
		try {
        Builder parser = new Builder();
        Document doc;
		doc = parser.build(authXmlPath);
        Element element = doc.getRootElement();
        for(int i = 0; i < element.getChildElements().size();i++){
        	if(element.getChildElements().get(i).getAttribute("list").getValue().toString().equals(playlist)){
        		element.getChildElements().get(i).detach();
        	}
        }
        writeXmlFile(doc, authXmlPath);
		} catch (ValidityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParsingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public String getOwner(String playlist){
    	String output = "";
    	playlist = playlist.toLowerCase().replaceAll("[^a-zA-Z]", "_");
		try {
        Builder parser = new Builder();
        Document doc;
		doc = parser.build(authXmlPath);
        Element element = doc.getRootElement();
        for(int i = 0; i < element.getChildElements().size();i++){
        	if(element.getChildElements().get(i).getAttribute("user").getValue().toString().equals(playlist)){
        		output = element.getChildElements().get(i).getAttribute("user").getValue().toString();
        	}
        }
		} catch (ValidityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParsingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return output;
    }
    

}
